package algorithm.linklist;

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public int len() {
        int len = 0;
        ListNode thisNode = this;
        while (thisNode.next != null) {
            len++;
            thisNode = thisNode.next;
        }
        return len;
    }

    public static ListNode getRandomNode(int len, int maxVal) {
        if (len <= 0) {
            return null;
        }
        ListNode result = new ListNode((int) (Math.random() * maxVal));
        len--;
        ListNode next = null;
        while (len != 0) {
            if (next == null) {
                result.next = new ListNode((int) (Math.random() * maxVal));
                next = result.next;
            } else {
                next.next = new ListNode((int) (Math.random() * maxVal));
                next = next.next;
            }
            len--;
        }
        return result;
    }

    public void print() {
        ListNode node = this;
        while (node != null) {
            System.out.print(" " + node.val);
            node = node.next;
        }
        System.out.println();
    }

    /**
     * 反转链表
     */
    public ListNode revert() {
        ListNode head = this;
        ListNode pre = null;
        ListNode next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre  = head;
            head = next;
        }
        return pre;
    }
}

